package de.mmis.core.base.gclass;

import java.lang.reflect.Array;
import java.util.List;

/**
 * represents an array of any type. The inner type is also a {@link GClass}
 * 
 * @author Christian Koch
 * 
 */
public class GArray extends GClass {
	private GClass componentType;

	/**
	 * creates new GArray instance with specified inner type
	 * 
	 * @param componentType
	 *            type of components of this array
	 */
	public GArray(GClass componentType) {
		this.setComponentType(componentType);
	}

	/**
	 * set component type of this Array
	 * 
	 * @param componentType
	 *            new component type
	 */
	public void setComponentType(GClass componentType) {
		this.componentType = componentType;
	}

	/**
	 * @return type of elements of this array
	 */
	public GClass getComponentType() {
		return this.componentType;
	}

	@Override
	protected void toStringInternal(StringBuilder sb) {
		this.componentType.toStringInternal(sb);
		sb.append("[]");
	}

	@Override
	public boolean equalsClass(Class<?> c) {
		if (!c.isArray())
			return false;
		return this.getComponentType().equalsClass(c.getComponentType());
	}

	@Override
	public Class<?> getBaseClass() {
		return Array.newInstance(componentType.getBaseClass(), 0).getClass();
	}

	@Override
	protected void collectClasses(List<Class<?>> classList) {
		this.componentType.collectClasses(classList);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((componentType == null) ? 0 : componentType.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		GArray other = (GArray) obj;
		if (componentType == null) {
			if (other.componentType != null)
				return false;
		} else if (!componentType.equals(other.componentType))
			return false;
		return true;
	}
}
